<template>
  <el-upload  ref="upload"
    v-model:file-list="fileList"
    class="upload-demo" name="image"
    :action="actionApi"
    multiple :auto-upload="auto"
    :headers="{ authorization: token, 'Request-from': 'Dashboard' }"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :limit="3"
    :on-exceed="handleExceed"
    :on-success="handleSuccess"
    :on-change="handleChange"
  >
    <el-button type="primary">Click to upload</el-button>
    <template #tip>
      <div class="el-upload__tip">
        jpg/png files with a size less than 2MB.
      </div>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import {formatToken, getToken} from "@/utils/auth";

const props = defineProps({
  action: {
    type: String,
    default: '/upload-file',
  },
  auto: {
    type: Boolean,
    default: true,
  },
  modelValue: {
    type: Object,
    default: [],
    require: true,
  },
  imageClass: {
    type: String,
    default: 'upload-img',
  },
  fileList: {
    type: Object,
    default: [],
  },
})
import type { UploadProps, UploadUserFile } from 'element-plus'
const emits = defineEmits(['update:modelValue'])
const actionApi = ref<string>('')
import {message} from "@/utils/message";
const { VITE_APP_BASE_API } = import.meta.env;
// actionApi.value = VITE_APP_BASE_API + props.action
// actionApi.value = actionApi.value.replace("//upload-file", "/upload-file")
actionApi.value = VITE_APP_BASE_API + (VITE_APP_BASE_API.endsWith('/')?'upload-file':'/upload-file')

const fileList = ref<UploadUserFile[]>([])
fileList.value = props.fileList
import { ElMessage, ElMessageBox } from 'element-plus'

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

const token = ref<string>()
token.value = formatToken(getToken().accessToken)

const handleSuccess = (response: any) => {
  if (response.code === 10000) {
    emits('update:modelValue', [...props.modelValue, response.data])
    emits('isUploading', false)
  } else {
    message(`失败，原因：${response.message}`, {type: "error"});
  }
}
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  console.log(6666,uploadFiles,uploadFiles.value)
}
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  )
}
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {

  const index = fileList.value.indexOf(file)
  if (index !== -1) {
    fileList.value.splice(index, 1)
  }
  emits('update:modelValue', fileList.value)
}
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}
</script>
